﻿using System;
using System.Collections.Generic;
using System.Linq;
using TestSystem.Model.Exceptions;

namespace TestSystem.Model.Data.Repositories
{
    public class FoldersRepository
    {
        private TestSystemEntities entities = new TestSystemEntities();

        public IQueryable<Folder> FindAll()
        {
            return entities.Folders.AsQueryable();
        }

        public Folder GetById(Int32 id)
            
        {
            
            return entities.Folders.SingleOrDefault(folder => folder.Id == id);
        }

        public void Insert(Folder folder)
        {
            if (entities.Folders.Any(f => f.Name.Equals(folder.Name, StringComparison.InvariantCultureIgnoreCase)))
                throw new EntityAlreadyExistsException("Such item already exists");

            entities.AddToFolders(folder);
        }

        public void Delete(Folder folder)
        {
            
            var currentTools = entities.Tools.Where(t => t.FolderId == folder.Id);
            var currentFrequencies = new FrequencyRepository();
            
            foreach (var tool in currentTools)
            {
                currentFrequencies.Delete(tool.Id);
                currentFrequencies.Save();
                entities.DeleteObject(tool);
                
            }
            entities.Folders.DeleteObject(folder);
        }

        public void Save()
        {
            entities.SaveChanges();
        }

        public void Dispose()
        {
            entities.Dispose();
        }

        public void Rename(Folder parent, string newname)
        {
            parent.Name = newname;
        }
    }
}
